package product_logic

import (
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
	"wx-uniapp-go/third_party/oss"
)

// ListCategory 获取分类列表
func (l *ProductLogic) ListCategory(req *dto.ListCategoryReq) (*dto.ListCategoryResp, error) {
	where := "status = ?"
	var params []interface{}
	params = append(params, 1) // 只查询启用状态的分类

	// 如果指定了父级ID，查询其子分类
	if req.ParentId != "" {
		where += " AND parent_id = ?"
		params = append(params, req.ParentId)
	} else {
		// 否则查询所有父级分类
		where += " AND parent_id = ''"
	}

	// 获取分类列表
	var categories []*models.ProductCategory
	err := models.Find(l.Ctx, &categories, where, params...)
	if err != nil {
		return nil, err
	}

	// 转换响应
	list := make([]dto.CategoryItem, len(categories))
	for i, category := range categories {
		list[i] = dto.CategoryItem{
			Id:       category.Id,
			Name:     category.Name,
			Text:     category.Text,
			Icon:     oss.Cli.JoinPath(category.Icon),
			Sort:     category.Sort,
			ParentId: category.ParentId,
			Level:    category.Level,
		}
	}

	return &dto.ListCategoryResp{
		List: list,
	}, nil
}
